package compositeMod;

import java.util.ArrayList;
import java.util.Iterator;

public class code {
    // 抽象类 Entry，定义了组合中对象的共有接口
    public abstract class Entry {
        public void add(Entry entry) {
            // 叶子节点不能添加子节点，所以这个方法可以不做实现或者抛出异常
            throw new UnsupportedOperationException("Cannot add to a Member.");
        }

        public abstract void share(String message);

        public abstract String getName();
    }

    // Member 类，继承自 Entry，表示组合中的叶子节点
    public class Member extends Entry {
        private String name;

        public Member(String name) {
            this.name = name;
        }

        @Override
        public void share(String message) {
            System.out.println(name + " shared: " + message);
        }

        @Override
        public String getName() {
            return name;
        }
    }

    // Group 类，继承自 Entry，表示组合中的组合节点
    public class Group extends Entry {
        private String name;
        private ArrayList<Entry> list = new ArrayList<>();

        public Group(String name) {
            this.name = name;
        }

        @Override
        public void add(Entry entry) {
            list.add(entry);
        }

        @Override
        public void share(String message) {
            System.out.println(name + " shared: " + message);
            Iterator<Entry> it = list.iterator();
            while (it.hasNext()) {
                Entry entry = (Entry) it.next();
                entry.share(message);
            }
        }

        @Override
        public String getName() {
            return name;
        }
    }

}
